package com.admin.education.common.openId;

import com.admin.education.common.response.IResponseMessage;
import com.admin.education.common.response.ResponseMessage;
import com.admin.education.common.response.Result;
import com.alibaba.fastjson.JSON;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class OpenIdInterceptor extends HandlerInterceptorAdapter {
    @Override
    public  boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (handler instanceof HandlerMethod) {
            OpenIdAuthorize openIdAuthorize = ((HandlerMethod) handler).getMethodAnnotation(OpenIdAuthorize.class);
            Object classJwtAuthorize = ((HandlerMethod) handler).getBean().getClass().getAnnotation(OpenIdAuthorize.class);
            if (null == openIdAuthorize && null == classJwtAuthorize)
            {
                return true;
            }
            if ("OPTIONS".equals(request.getMethod())) {
                response.setStatus(HttpServletResponse.SC_OK);
                return true;
            }
            else{
                final String openIdHeader = request.getHeader("OpenId");
                String accept =  request.getHeader("Accept");
                IResponseMessage responseMessage = null;
                if (openIdHeader == null){
                    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                    if("application/json".equals(accept)) {
                        responseMessage =new ResponseMessage(Result.Error,"请输入正确的OpenId");
                        response.getWriter().print(JSON.toJSON(responseMessage));
                    }
                    return  false;
                }
                return true;
            }
        }
        return true;
    }
}
